import axios from 'axios';
import {message} from 'antd';

const api = axios.create({
    timeout: 50000,
});

// 请求拦截器
api.interceptors.request.use(
    config => {
        const token = localStorage.getItem('access_token');
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
    },
    error => {
        return Promise.reject(error.response.data)
    }
);

// 响应拦截器
api.interceptors.response.use(
    response => {
        if (response.data.code === 401) {
            message.error('登录失效，请重新登录')
            localStorage.removeItem('access_token')
            localStorage.removeItem('refresh_token')
            localStorage.removeItem('user_info')
            window.location.href = '/login'
            location.reload()
        }
        return response
    },
    async error => {
        return Promise.reject(error.response.data);
    }
);

export default api;